package com.main.util;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 单利模式加载配置文件读取
 * @author wz
 *
 */
public class PropertiesUtil {
    
	private static PropertiesUtil pu;
    
    private Map<String,Properties> proMap=new HashMap<String,Properties>();
	
    private PropertiesUtil(){}
	
    public static PropertiesUtil getProtertiesUtil(){
		if(null!=pu){
			return pu;
		}else{
			pu=new PropertiesUtil();
			return pu;
		}
	}
    
    /**
     * 实例化
     * @throws IOException 
     */
    public void init(){
    	//获取WEB-INF/class路径
    	String path=PropertiesUtil.class.getResource("/").toString().substring(6)+"config/";
    	File proParent=new File(path);
    	if(proParent.isDirectory()){
    		File files[]=proParent.listFiles(new FileFilter() {
				@Override
				public boolean accept(File pathname) {
					if(pathname.getName().toLowerCase().endsWith("properties")){
						return true;
					}
					return false;
				}
			});
    	  for(File f:files){
    		  Properties prop = new Properties();//属性集合对象      
    		  FileInputStream fis;
			try {
				fis = new FileInputStream("prop.properties");
				prop.load(fis);//将属性文件流装载到Properties对象中
				fis.close();
				proMap.put(f.getName(), prop);
			} catch (IOException e) {
				e.printStackTrace();
			}
    	  }	
    	}
    }
    
    /**
     * 清空
     */
    public void destory(){
    	proMap.clear();
    }
    
    /**
     * 重新加载
     * @throws IOException 
     */
    public void reload() throws IOException{
    	this.destory();
    	this.init();
    }
    
    /**
     * 获取配置文件
     * @param fileName
     * @param key
     * @return
     */
    public String getProperties(String fileName,String key){
    	if(null!=fileName){
    		if(!fileName.toLowerCase().endsWith(".properties")){
    			fileName+=".properties";
    		}
    		if(proMap.containsKey(fileName))
    		 return proMap.get(fileName).getProperty(key);
    		else
    		 return null;
    	}else{
    		return null;
    	}
    }
}
